package com.phpxiu.app.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.LoginModeContent;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.response.LoginMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.push.MessageEvent;
import com.phpxiu.app.push.PushUtil;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.MEditText;
import com.phpxiu.app.view.custom.WindowLayout;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.tencent.TIMOfflinePushSettings;
import com.tencent.TIMUser;
import com.tencent.av.sdk.AVError;
import com.tencent.bugly.imsdk.crashreport.CrashReport;


/**
 * Created by WuJinZhou on 2016/5/3.
 */
public class LoginByPhone extends UIBase implements View.OnClickListener,TextWatcher,TIMCallBack {
    public final static String TAG="LoginByPhone";
    public final static int REQUEST_REGISTER_CODE=0x1;
    public final static int REQUEST_RESET_PWD_CODE=0x2;
    public final static int REQUEST_PICK_COUNTRY_CODE=0x3;
    private WindowLayout mainView;
    private TextView regionsView;//区域名称
    private TextView countryCodeView;//区号
    private MEditText accountInput;
    private MEditText pwdInput;
    private PasswordTextWatcher pwdTextWatcher;
    private ImageButton cleanAccount,cleanPwd;
    private Button submitBtn;
    private boolean isRequesting=false;//提交中，不能重复提交
    private String countryCode="";//国际电话区号
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_by_phone);
        init();
    }

    final private void init(){
        mainView=(WindowLayout)findViewById(R.id.login_by_phone_root_view);
        mainView.setOnClickListener(this);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        findViewById(R.id.register_btn).setOnClickListener(this);
        findViewById(R.id.pick_country_link).setOnClickListener(this);
        findViewById(R.id.goto_reset_pwd_btn).setOnClickListener(this);
        regionsView=(TextView)findViewById(R.id.country_name);
        regionsView.setText(getString(R.string.default_country_name));
        countryCodeView=(TextView)findViewById(R.id.country_code);
        countryCode=getString(R.string.default_region_code);
        countryCodeView.setText("+"+countryCode);
        accountInput=(MEditText)findViewById(R.id.login_phone_number_input);
        accountInput.addTextChangedListener(this);
        cleanAccount=(ImageButton)findViewById(R.id.phone_number_input_clean_btn);
        cleanAccount.setOnClickListener(this);
        pwdInput=(MEditText)findViewById(R.id.login_pwd_input);
        pwdTextWatcher=new PasswordTextWatcher();
        pwdInput.addTextChangedListener(pwdTextWatcher);
        cleanPwd=(ImageButton)findViewById(R.id.password_input_clean_btn);
        cleanPwd.setOnClickListener(this);
        submitBtn=(Button)findViewById(R.id.login_by_phone_submit);
        submitBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.pick_country_link:
                pickCountryCode();
                break;
            case R.id.phone_number_input_clean_btn:
                accountInput.setText("");
                break;
            case R.id.password_input_clean_btn:
                pwdInput.setText("");
                break;
            case R.id.login_by_phone_submit:
                login();
            case R.id.login_by_phone_root_view:
                hideSoftBoard();
                break;
            case R.id.register_btn:
                gotoRegister();
                break;
            case R.id.goto_reset_pwd_btn:
                gotoResetPwd();
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(TextUtils.isEmpty(s)){
            if(cleanAccount.getVisibility()==View.VISIBLE){
                cleanAccount.setVisibility(View.INVISIBLE);
            }
        }else{
            if(cleanAccount.getVisibility()!=View.VISIBLE){
                cleanAccount.setVisibility(View.VISIBLE);
            }
        }
        checkCanSubmit();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    /**
     * 检测是否可以点击提交表单
     */
    public void checkCanSubmit(){
        boolean accountValid=!TextUtils.isEmpty(accountInput.getText())&&TextUtils.getTrimmedLength(accountInput.getText())>5;
        boolean pwdValid=TextUtils.getTrimmedLength(pwdInput.getText())>=6;
        if(accountValid&&pwdValid){
            if(!submitBtn.isEnabled()){
                submitBtn.setEnabled(true);
            }
        }else{
            if(submitBtn.isEnabled()){
                submitBtn.setEnabled(false);
            }
        }
    }


    /**
     * 请求登录
     */
    final private void login() {
        if(isRequesting){
            return;
        }
        isRequesting=true;
        final String account=(countryCode+accountInput.getText().toString()).trim();
        final String pwd=pwdInput.getText().toString().trim();
        OKHttpParam param= OKHttpParam.builder();
        param.put("phone",account);
        param.put("password",pwd);
        OKHttp.post(HttpConfig.API_LOGIN_WITH_PASSWORD, param.jsonParam(), TAG, new OKHttpUIHandler(LoginMode.class) {
            @Override
            public void onSuccess(Object model) {
                isRequesting = false;
                LoginMode m = (LoginMode) model;
                KKYUtil.log(TAG, "手机登录结果:" + m.getResponseStr());
                if (m.getData() != null) {
                    loginSuccess(m.getData());
                } else {
                    mainView.showTopMsg(getString(R.string.login_failed));
                }

            }

            @Override
            public void onErr(String errMsg) {
                isRequesting = false;
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 去注册
     */
    final private void gotoRegister(){
        hideSoftBoard();
        Intent register=new Intent(this,UIRegister.class);
        startActivityForResult(register,REQUEST_REGISTER_CODE);
    }
    /**
     * 选择国际区号
     */
    final private void pickCountryCode(){
        Intent pick=new Intent(this,UICountryCodePicker.class);
        startActivityForResult(pick,REQUEST_PICK_COUNTRY_CODE);
    }

    /**
     *忘记密码,去重置
     */
     private void gotoResetPwd(){
         hideSoftBoard();
         Intent resetPwd=new Intent(this,UIResetPwd.class);
         startActivityForResult(resetPwd,REQUEST_RESET_PWD_CODE);
    }

    /**
     * 隐藏输入软盘
     */
    final private void hideSoftBoard(){
        View view =getCurrentFocus();
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_REGISTER_CODE){//注册成功
            if(resultCode==RESULT_OK){
                setResult(RESULT_OK);
                finish();
            }
        }else if(requestCode==REQUEST_RESET_PWD_CODE){//重置密码成功
            if(resultCode==RESULT_OK){
                setResult(RESULT_OK);
                finish();
            }
        }else if(requestCode==REQUEST_PICK_COUNTRY_CODE){//选择国际区号结果
            if(resultCode==RESULT_OK){
                countryCode=data.getStringExtra(UICountryCodePicker.SELECTED_CODE);
                String regionName=data.getStringExtra(UICountryCodePicker.SELECTED_COUNTRY);
                regionsView.setText(regionName);
                countryCodeView.setText("+"+countryCode);
            }
        }
    }


    /**
     * 登录成功结果
     * @param result
     */
    private void loginSuccess(LoginModeContent result){
        KKYUtil.log("上传签名：" + result.getCossig());
        MySelfInfo.getInstance().setId(result.getUserinfo().getUid());
        MySelfInfo.getInstance().setUserSig(result.getSig());
        MySelfInfo.getInstance().setNickName(result.getUserinfo().getNickname());
        MySelfInfo.getInstance().setAvatar(result.getUserinfo().getAvatar());
        MySelfInfo.getInstance().setSign(result.getUserinfo().getIntro());
        MySelfInfo.getInstance().setCosSig(result.getCossig());
        try {
            int roomNum = Integer.parseInt(result.getUserinfo().getRoomid());
            MySelfInfo.getInstance().setMyRoomNum(roomNum);
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMobilenum(result.getUserinfo().getMobilenum());
        MySelfInfo.getInstance().setSex(result.getUserinfo().getSex());
        MySelfInfo.getInstance().setAddress(result.getUserinfo().getAddress());
        MySelfInfo.getInstance().setVerifyState(result.getUserinfo().getApproved());
        try {
            MySelfInfo.getInstance().setMoney(Long.parseLong(result.getUserinfo().getMoney()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        try {
            MySelfInfo.getInstance().setLvl(Integer.parseInt(result.getUserinfo().getLvl()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMerrage(result.getUserinfo().getMerrage());
        try {
            MySelfInfo.getInstance().setAge(Integer.parseInt(result.getUserinfo().getAge()));
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        MySelfInfo.getInstance().writeToCache(this);
        IMLogin(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
    }

    /**
     * 登录IM
     * @param identify 用户id
     * @param userSig//登录获取的签名
     */
    private void IMLogin(String identify,String userSig){
        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        //发起登录请求
        TIMManager.getInstance().login(Constants.SDK_APPID, user, userSig, LoginByPhone.this);
    }

    /**
     * IM 登录失败
     * @param i
     * @param s
     */
    @Override
    public void onError(int i, String s) {
        if(i==6012){
            mainView.showTopMsg(getString(R.string.login_failed));
        }
        //发送日志到错误统计
        CrashReport.postCatchedException(new Throwable("Main IM Login failed：" + i + "-->" + s));
        if(KKYUtil.DEBUG){
            mainView.showTopMsg(i + "-->" + s);
        }
    }

    /**
     * IM登录成功
     */
    @Override
    public void onSuccess() {
        TIMOfflinePushSettings SETTINGS = new TIMOfflinePushSettings();
        SETTINGS.setEnabled(true);
        TIMManager.getInstance().configOfflinePushSettings(SETTINGS);
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        if(startAVSDK()){
            Intent main=new Intent(LoginByPhone.this,Main.class);
            startActivity(main);
            setResult(RESULT_OK);
            finish();
        }else{
            mainView.showTopMsg(getString(R.string.login_failed));
            CrashReport.postCatchedException(new Exception("登录失败,AV SDK初始化失败"));
        }
    }

    /**
     * 初始化音视频SDK
     */
    public static boolean startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(Constants.SDK_APPID, "" + Constants.ACCOUNT_TYPE, MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        int startResult=QavsdkControl.getInstance().startContext();
        if(startResult!=AVError.AV_OK){
            return false;
        }
        return true;
    }

    /**
     * 密码输入监听
     */
    class PasswordTextWatcher implements TextWatcher{
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(TextUtils.isEmpty(s)){
                if(cleanPwd.getVisibility()==View.VISIBLE){
                    cleanPwd.setVisibility(View.INVISIBLE);
                }
            }else{
                if(cleanPwd.getVisibility()!=View.VISIBLE){
                    cleanPwd.setVisibility(View.VISIBLE);
                }
            }
            checkCanSubmit();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
